#!/usr/bin/env python
# -*- coding: utf-8 -*-
from flask import jsonify, request
from flask_restful import Resource
from utility.error_code import error_code
import logging
from utility import tools
import psycopg2


FORMAT = "%(asctime)s %(thread)d %(message)s"
logging.basicConfig(level=logging.INFO, format=FORMAT)
database = "chanke"
user = "odoo"
password = "Odoo!Db@2023$"
host = "140.246.134.213"
port = "5436"


class ZhuYuanFenMianListAPI(Resource):
    """
    住院分娩月报
    :request: post
    :param fmsjStart: 分娩时间开始日期
    :param fmsjEnd: 分娩时间结束日期
    :param isAsc：排序方向 排序的方向,示例值(asc,desc)
    :param orderByColumn：排序列
    :param pageNum：当前页数
    :param pageSize: 分页大小
    :returns: json string
    """

    def post(self):
        try:
            params = tools.get_params(request)
            examDateStart = params.get('fmsjStart')  # 检查日期开始
            examDateEnd = params.get('fmsjEnd')  # 检查日期结束
            isAsc = params.get('isAsc')  # 排序方向 排序的方向,示例值(asc,desc)
            orderByColumn = params.get('orderByColumn')  # 排序列
            pageNum = params.get('pageNum')  # 当前页数
            pageSize = params.get('pageSize')  # 分页大小
            sql = ''
            sqlCount = ''
            condition = ''
            IsFirst = False
            # 获取数据部分
            datalist = []
            return jsonify({
                'code': 200,
                'data': {
                    'dataList': datalist,
                    'total': 1
                },
                'msg': 'success',
                'success': True
            })
        except Exception as e:
            logging.exception(e)
            return jsonify({'code': 100, 'msg': error_code[100], 'success': False, 'data': ''})


class TangShaiCaseListAPI(Resource):
    """
    唐筛个案登记本
    :request: post
    :param examDateStart: 检查日期开始
    :param examDateEnd: 检查日期结束
    :param djDateStart: 登记日期开始
    :param djDateEnd: 登记日期结束
    :param fxbz: 风险标志
    :param djrCode: 登记人Code
    :param searchText: 搜索内容
    :param isAsc：排序方向 排序的方向,示例值(asc,desc)
    :param orderByColumn：排序列
    :param pageNum：当前页数
    :param pageSize: 分页大小
    :returns: json string
    """

    def post(self):
        try:
            return GetData('唐筛')
        except Exception as e:
            logging.exception(e)
            return jsonify({'code': 100, 'msg': error_code[100], 'success': False, 'data': ''})


class NTListAPI(Resource):
    """
    NT个案登记本
    :request: post
    :param examDateStart: 检查日期开始
    :param examDateEnd: 检查日期结束
    :param djDateStart: 登记日期开始
    :param djDateEnd: 登记日期结束
    :param daStatus:档案状态
    :param fxbz: 风险标志
    :param djrCode: 登记人Code
    :param searchText: 搜索内容
    :param isAsc：排序方向 排序的方向,示例值(asc,desc)
    :param orderByColumn：排序列
    :param pageNum：当前页数
    :param pageSize: 分页大小
    :returns: json string
    """

    def post(self):
        try:
            return GetData('NT')
        except Exception as e:
            logging.exception(e)
            return jsonify({'code': 100, 'msg': error_code[100], 'success': False, 'data': ''})


class TangNaiListAPI(Resource):
    """
    糖耐OGTT个案登记本
    :request: post
    :param examDateStart: 检查日期开始
    :param examDateEnd: 检查日期结束
    :param djDateStart: 登记日期开始
    :param djDateEnd: 登记日期结束
    :param daStatus:档案状态
    :param fxbz: 风险标志
    :param djrCode: 登记人Code
    :param searchText: 搜索内容
    :param isAsc：排序方向 排序的方向,示例值(asc,desc)
    :param orderByColumn：排序列
    :param pageNum：当前页数
    :param pageSize: 分页大小
    :returns: json string
    """

    def post(self):
        try:
            return GetData('糖耐')
        except Exception as e:
            logging.exception(e)
            return jsonify({'code': 100, 'msg': error_code[100], 'success': False, 'data': ''})


class AiMeiYiListAPI(Resource):
    """
    艾梅乙登记本
    :request: post
    :param examDateStart: 检查日期开始
    :param examDateEnd: 检查日期结束
    :param djDateStart: 登记日期开始
    :param djDateEnd: 登记日期结束
    :param daStatus:档案状态
    :param yxxm: 阳性项目
    :param djrCode: 登记人Code
    :param searchText: 搜索内容
    :param isAsc：排序方向 排序的方向,示例值(asc,desc)
    :param orderByColumn：排序列
    :param pageNum：当前页数
    :param pageSize: 分页大小
    :returns: json string
    """

    def post(self):
        try:
            return GetData('艾梅乙')
        except Exception as e:
            logging.exception(e)
            return jsonify({'code': 100, 'msg': error_code[100], 'success': False, 'data': ''})


def GetData(LeiBie):
    params = tools.get_params(request)
    examDateStart = params.get('examDateStart')  # 检查日期开始
    examDateEnd = params.get('examDateEnd')  # 检查日期结束
    djDateStart = params.get('djDateStart')  # 登记日期开始
    djDateEnd = params.get('djDateEnd')  # 登记日期结束
    daStatus = ''
    if LeiBie == '糖耐' or LeiBie == 'NT' or LeiBie == '艾梅乙':
        daStatus = params.get('daStatus')  # 档案状态
    yxxm = ''
    if LeiBie == '艾梅乙':
        yxxm = params.get('yxxm')  # 阳性项目
    fxbz = ''
    if LeiBie != '艾梅乙':
        fxbz = params.get('fxbz')  # 风险标志
    djrCode = params.get('djrCode')  # 登记人Code
    searchText = params.get('searchText')  # 搜索内容
    isAsc = params.get('isAsc')  # 排序方向 排序的方向,示例值(asc,desc)
    orderByColumn = params.get('orderByColumn')  # 排序列
    pageNum = params.get('pageNum')  # 当前页数
    pageSize = params.get('pageSize')  # 分页大小
    sql = ''
    sqlCount = ''
    condition = ''
    IsFirst = False
    if LeiBie == 'NT':
        sql = 'select a.mzh,a.mq_xm,a.mq_age,a.yz,a.mq_sfz,a.mq_cz_province,a.mq_cz_city,a.mq_cz_county,a.mq_sjhm,' \
              'b.sc_jg,b.jc_date,b.jc_jg,b.dj_r,b.dj_date,' \
              'a.status from inspection_nt_screen b left join res_archives a ' \
              'on b.archives_id=a.id '
        sqlCount = 'select count(b.id) from inspection_nt_screen b left join res_archives a on b.archives_id=a.id '
    elif LeiBie == '糖耐':
        sql = 'select a.mzh,a.mq_xm,a.mq_age,a.yz,a.mq_sfz,a.mq_cz_province,a.mq_cz_city,a.mq_cz_county,a.mq_sjhm,' \
              'b.kg_ptt,b.yxs_ptt,b.lxs_ptt,b.jg,b.jc_date,b.jc_jg,b.dj_r,b.dj_date,' \
              'a.status from inspection_sugar_resistance b left join res_archives a ' \
              'on b.archives_id=a.id '
        sqlCount = 'select count(b.id) from inspection_sugar_resistance b left join res_archives a on b.archives_id=a.id '
    elif LeiBie == '唐筛':
        sql = 'select a.mzh,a.mq_xm,a.mq_sfz,a.mq_cz_province,a.mq_cz_city,a.mq_cz_county,a.mq_sjhm,' \
              'b.st21_jcjg,b.st18_jcjg,b.ntd_jcjg,b.free_mom,b.app_mom,b.e3_mom,b.risk_tag,' \
              'b.jbxx_csyz,b.jbxx_cyrq,b.jbxx_jcrq from inspection_tang_case b left join res_archives a ' \
              'on b.archives_id=a.id '
        sqlCount = 'select count(b.id) from inspection_tang_case b left join res_archives a on b.archives_id=a.id '
    elif LeiBie == '艾梅乙':
        sql = 'select a.mzh,a.mq_xm,a.mq_age,a.yz,a.mq_sfz,a.mq_cz_province,a.mq_cz_city,a.mq_cz_county,a.mq_sjhm,' \
              'b.hiv_jcjg,b.hiv_jcrq,b.hiv_jcjg_id,b.hiv_jcjg_name,b.md_jcjg,b.md_jcrq,b.md_jcjg_id,b.md_jcjg_name,' \
              'b.yg_jcjg,b.yg_jcrq,b.yg_jcjg_id,b.yg_jcjg_name,b.register_user,b.register_date,a.status ' \
              'from inspection_amy b left join res_archives a on b.archives_id=a.id '
        sqlCount = 'select count(b.id) from inspection_amy b left join res_archives a on b.archives_id=a.id '
    if examDateStart != '':
        IsFirst = True
        if LeiBie == '糖耐' or LeiBie == 'NT':
            condition = ' where b.jc_date >= \'' + examDateStart + '\''
        elif LeiBie == '唐筛':
            condition = ' where b.jbxx_jcrq >= \'' + examDateStart + '\''
    if examDateEnd != '':
        if IsFirst:
            if LeiBie == '糖耐' or LeiBie == 'NT':
                condition = condition + ' and b.jc_date <= \'' + examDateEnd + '\''
            elif LeiBie == '唐筛':
                condition = condition + ' and b.jbxx_jcrq <= \'' + examDateEnd + '\''
        else:
            IsFirst = True
            if LeiBie == '糖耐' or LeiBie == 'NT':
                condition = ' where b.jc_date <= \'' + examDateEnd + '\''
            elif LeiBie == '唐筛':
                condition = ' where b.jbxx_jcrq <= \'' + examDateEnd + '\''
    if djDateStart != '':
        if IsFirst:
            if LeiBie == '糖耐' or LeiBie == 'NT':
                condition = condition + ' and b.dj_date >= \'' + djDateStart + '\''
            elif LeiBie == '唐筛':
                condition = condition + ' and b.jbxx_djrq >= \'' + djDateStart + '\''
            elif LeiBie == '艾梅乙':
                condition = condition + ' and b.register_date >= \'' + djDateStart + '\''
        else:
            IsFirst = True
            if LeiBie == '糖耐' or LeiBie == 'NT':
                condition = ' where b.dj_date >= \'' + djDateStart + '\''
            elif LeiBie == '唐筛':
                condition = ' where b.jbxx_djrq >= \'' + djDateStart + '\''
            elif LeiBie == '艾梅乙':
                condition = ' where b.register_date >= \'' + djDateStart + '\''
    if djDateEnd != '':
        if IsFirst:
            if LeiBie == '糖耐' or LeiBie == 'NT':
                condition = condition + ' and b.dj_date <= \'' + djDateEnd + '\''
            elif LeiBie == '唐筛':
                condition = condition + ' and b.jbxx_djrq <= \'' + djDateEnd + '\''
            elif LeiBie == '艾梅乙':
                condition = condition + ' and b.register_date <= \'' + djDateEnd + '\''
        else:
            IsFirst = True
            if LeiBie == '糖耐' or LeiBie == 'NT':
                condition = ' where b.dj_date <= \'' + djDateEnd + '\''
            elif LeiBie == '唐筛':
                condition = ' where b.jbxx_djrq <= \'' + djDateEnd + '\''
            elif LeiBie == '艾梅乙':
                condition = ' where b.register_date <= \'' + djDateEnd + '\''
    if daStatus != '':
        if IsFirst:
            condition = condition + ' and a.status = \'' + daStatus + '\''
        else:
            IsFirst = True
            condition = ' where a.status = \'' + daStatus + '\''
    if fxbz != '':
        if IsFirst:
            if LeiBie == 'NT':
                if fxbz == '低风险':
                    condition = condition + ' and b.sc_jg <= \'' + fxbz + '\''
                elif fxbz == '高风险':
                    condition = condition + ' and b.sc_jg > \'' + fxbz + '\''
            elif LeiBie == '糖耐':  # 糖耐OGTT个案登记本
                condition = condition + ' and b.jg = \'' + fxbz + '\''
            elif LeiBie == '唐筛':
                condition = condition + ' and b.risk_tag = \'' + fxbz + '\''
        else:
            IsFirst = True
            if LeiBie == 'NT':
                if fxbz == '低风险':
                    condition = ' where b.sc_jg <= \'' + fxbz + '\''
                elif fxbz == '高风险':
                    condition = ' where b.sc_jg > \'' + fxbz + '\''
            elif LeiBie == '糖耐':  # 糖耐OGTT个案登记本
                condition = ' where b.jg = \'' + fxbz + '\''
            elif LeiBie == '唐筛':
                condition = ' where b.risk_tag = \'' + fxbz + '\''
    if yxxm != '':
        if yxxm == 'HIV':
            if IsFirst:
                condition = condition + ' and b.hiv_jcjg = \'阳性\''
            else:
                IsFirst = True
                condition = ' where b.hiv_jcjg = \'阳性\''
        elif yxxm == '梅毒':
            if IsFirst:
                condition = condition + ' and b.md_jcjg = \'阳性\''
            else:
                IsFirst = True
                condition = ' where b.md_jcjg = \'阳性\''
        elif yxxm == '乙肝':
            if IsFirst:
                condition = condition + ' and b.yg_jcjg = \'阳性\''
            else:
                IsFirst = True
                condition = ' where b.yg_jcjg = \'阳性\''
    if djrCode != '':
        if IsFirst:
            if LeiBie == '糖耐' or LeiBie == 'NT':
                condition = condition + ' and b.dj_r like \'%' + djrCode + '%\''
            elif LeiBie == '唐筛':
                condition = condition + ' and b.djr_name like \'%' + djrCode + '%\''
            elif LeiBie == '艾梅乙':
                condition = condition + ' and b.register_user like \'%' + djrCode + '%\''
        else:
            IsFirst = True
            if LeiBie == '糖耐' or LeiBie == 'NT':
                condition = ' where b.dj_r like \'%' + djrCode + '%\''
            elif LeiBie == '唐筛':
                condition = ' where b.djr_name like \'%' + djrCode + '%\''
            elif LeiBie == '艾梅乙':
                condition = ' where b.register_user like \'%' + djrCode + '%\''
    if searchText != '':
        if IsFirst:
            condition = condition + ' and concat(\'a.mq_xm\',\'a.mq_sfz\',\'a.mq_sjhm\',\'a.mzh\') = \'' + searchText + '\''
        else:
            condition = ' where concat(\'a.mq_xm\',\'a.mq_sfz\',\'a.mq_sjhm\',\'a.mzh\') = \'' + searchText + '\''
    sqlCount = sqlCount + condition
    if isAsc != '' and orderByColumn != '':
        if isAsc == 'asc':
            condition = condition + ' order by ' + orderByColumn
        elif isAsc == 'desc':
            condition = condition + ' order by ' + orderByColumn + ' desc '
    condition = condition + ' limit ' + pageSize + ' offset ' + str((int(pageNum) - 1) * int(pageSize))
    sql = sql + condition
    conn = psycopg2.connect(database=database, user=user, password=password, host=host, port=port)
    cursor = conn.cursor()
    cursor.execute(sql)
    results = cursor.fetchall()
    cursor.execute(sqlCount)
    total = cursor.fetchall()[0][0]
    cursor.close()
    conn.close()
    datalist = []
    k = 1
    if results:
        for result in results:
            if LeiBie == '糖耐':
                datalist.append({
                    'bh': str(k),
                    'mzh': result[0],
                    'xm': result[1],
                    'age': result[2],
                    'jcyz': result[3],
                    'idCard': result[4],
                    'addr': str(result[5]) + str(result[6]) + str(result[7]),
                    'phone': result[8],
                    'scjg': {
                        'xtkf': result[9],
                        'xt1Hour': str(result[10]),
                        'xt2Hour': result[11],
                        'fxbz': result[12],
                        'jcrq': str(result[13]),
                        'jcjgName': result[14]
                    },
                    'djrName': result[15],
                    'djrq': str(result[16]),
                    'daStatus': result[17]
                })
            elif LeiBie == 'NT':
                temp = '低风险'
                if float(result[9]) > 2.5:
                    temp = '高风险'
                datalist.append({
                    'bh': str(k),
                    'mzh': result[0],
                    'xm': result[1],
                    'age': result[2],
                    'jcyz': result[3],
                    'idCard': result[4],
                    'addr': str(result[5]) + str(result[6]) + str(result[7]),
                    'phone': result[8],
                    'scjg': {
                        'nt': result[9],
                        'fxbz': temp,
                        'jcrq': str(result[10]),
                        'jcjgName': result[11],
                    },
                    'djrName': result[12],
                    'djrq': str(result[13]),
                    'daStatus': result[14]
                })
            elif LeiBie == '唐筛':
                datalist.append({
                    'hm': str(k),
                    'mzh': result[0],
                    'xm': result[1],
                    'idCard': result[2],
                    'addr': str(result[3]) + str(result[4]) + str(result[5]),
                    'phone': result[6],
                    'scjg': {
                        'fx21': result[7],
                        'fx18': result[8],
                        'ntd': result[9],
                        'hcg': result[10],
                        'afp': result[11],
                        'ue3': result[12]
                    },
                    'fxbz': result[13],
                    'zsyz': result[14],
                    'cyrq': str(result[15]),
                    'jcrq': str(result[16])
                })
            elif LeiBie == '艾梅乙':
                datalist.append({
                    'bh': str(k),
                    'mzh': result[0],
                    'xm': result[1],
                    'age': result[2],
                    'jcyz': result[3],
                    'idCard': result[4],
                    'addr': str(result[5]) + str(result[6]) + str(result[7]),
                    'phone': result[8],
                    'scjg': {
                        'Hiv':
                            {
                                'jg': result[9],
                                'jcrq': str(result[10]),
                                'jcjgCode': result[11],
                                'jcjgName': result[12]
                            },
                        'md':
                            {
                                'jg': result[13],
                                'jcrq': str(result[14]),
                                'jcjgCode': result[15],
                                'jcjgName': result[16]
                            },
                        'yg':
                            {
                                'jg': result[17],
                                'jcrq': str(result[18]),
                                'jcjgCode': result[19],
                                'jcjgName': result[20]
                            }
                    },
                    'djrName': result[21],
                    'djrq': str(result[22]),
                    'daStatus': result[23]
                })
            k = k + 1
    return jsonify({
        'code': 200,
        'data': {
            'dataList': datalist,
            'total': total
        },
        'msg': 'success',
        'success': True
    })
